import * as fs from 'node:fs'
import * as path from 'node:path'
import { commonInfo, description } from './common'

export function makeApp(folderPath: string): void {
    try {
        const appJsonPath = path.join(folderPath, 'AppScope', 'app.json')
        const appJsonStr = fs.readFileSync(appJsonPath, { encoding: 'utf8', flag: 'r' })
        const appJson = JSON.parse(appJsonStr)
        if (appJson.app?.targetAPIVersion !== undefined) {
            console.info('\x1b[34m%s\x1b[0m', 'The old SDK version is ' + appJson.app.targetAPIVersion)
        }
        const appJson5 = makeDefaultAppJson5()
        for (const key in appJson5.app) {
            if (appJson.app?.[key] !== undefined) {
                (appJson5.app as any)[key] = appJson.app[key]
            }
        }
        const appJson5Str = JSON.stringify(appJson5, null, 2)
        fs.writeFileSync(path.join(folderPath, 'AppScope', 'app.json5'), description + '\n' + appJson5Str, 'utf8')
        if (appJson5.app.bundleName === 'ERROR_NO_BUNDLE_NAME') throw new Error('bundleName is not found')
        fs.unlinkSync(appJsonPath)
    } catch (err) {
        console.error('Error: ' + err)
        console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        console.warn('\x1b[33m%s\x1b[0m', `WARNING AppScope/app.json5 is not created. Please add app.json5 manually.`)
        console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
    }
}

function makeDefaultAppJson5() {
    return { app: {
        bundleName: commonInfo.bundleName ?? 'ERROR_NO_BUNDLE_NAME',
        vendor: 'huawei',
        versionCode: 1000000,
        versionName: '1.0.0',
        icon: '$media:app_icon',
        label: '$string:app_name'
    }}
}
